﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;

namespace TbDataSync
{
    public partial class Program
    {

        /// <summary>
        /// 推送属性数据
        /// </summary>
        /// <param name="deviceId"></param>
        /// <param name="content"></param>
        public static void PushAttr(string deviceId, HttpContent content)
        {
            var token = GetToken(deviceId, new_client);
            var pushAttrUrl = urls["post_attr"].Replace("%token%", token);
            var postresult = new_client.PostAsync(pushAttrUrl, content).Result;
            Log.Info($"目标设备属性数据已推送 设备ID:{deviceId}");
        }

        /// <summary>
        /// 获取属性数据
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        public static HttpContent GetAttr(string deviceId)
        {
            var exclude = new string[] { "active", "inactivityAlarmTime", "lastActivityTime" };
            var attrUrl = urls["attr_list"].Replace("%deviceId%", deviceId);
            var attr_result = new List<AttrListResult>();
            var attrResult = old_client.GetAsync(attrUrl).Result.Content.ReadAsStringAsync().Result;
            attr_result = JsonConvert.DeserializeObject<List<AttrListResult>>(attrResult);
            if (attr_result == null || attr_result.Count == 0)
            {
                Log.Info($"源设备属性数据为空,跳过 设备ID:{deviceId}");
                return null;
            }
            var attr_refrence = attr_result.Where(a => !exclude.Contains(a.key)).ToList();
            var body = "{";
            foreach (var attr in attr_refrence)
            {
                double r_l = 0;
                var f = attr.value.ToString();
                if (double.TryParse(f, out r_l) || f.StartsWith("{"))
                {
                    body += $"\"{attr.key}\":{attr.value},";
                }
                else
                {
                    body += $"\"{attr.key}\":\"{attr.value}\",";
                }

            }
            body = body.Substring(0, body.Length - 1) + "}";
            var content = new StringContent(body, Encoding.UTF8, "application/json");
            Log.Info($"源设备属性数据已获取 设备ID:{deviceId}");
            Wait();
            return content;
        }
    }
}
